<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="选择能耗表" prop="energyId">
        <el-select
          v-model="formData.energyId"
          placeholder="请选择能耗表"
          clearable
          class="w-full"
          @change="handleEnergyChange"
        >
          <el-option
            v-for="item in energyOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="所属车间" prop="workshopId">
        <el-select
          v-model="formData.workshopId"
          placeholder="请选择所属车间"
          clearable
          class="w-full"
          @change="handleWorkshopChange"
        >
          <el-option
            v-for="item in workshopOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="选择单位" prop="unitId">
        <el-select
          v-model="formData.unitId"
          placeholder="请选择能耗单位"
          clearable
          class="w-full"
          @change="handleUnitChange"
        >
          <el-option
            v-for="item in unitOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择日期" prop="energyTime">
        <el-date-picker
          class="w-full"
          style="width: 100%"
          v-model="formData.energyTime"
          type="date"
          value-format="x"
          placeholder="选择能耗时间"
        />
      </el-form-item>
      <el-form-item label="能耗值" prop="energyValue">
        <el-input v-model="formData.energyValue" placeholder="请输入能耗值" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { EnergyReportApi, EnergyReportVO } from '@/api/erp/energy/energyreport'
import { EnergyApi } from '@/api/erp/energy/energy'
import { EnergyWorkshopApi } from '@/api/erp/energy/energyworkshop'
import { EnergyUnitApi } from '@/api/erp/energy/energyunit'

/** ERP 能耗报表 表单 */
defineOptions({ name: 'EnergyReportForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const energyOptions = ref<{ id: number; name: string }[]>([]) // 能耗表选项列表
const workshopOptions = ref<{ id: number; name: string }[]>([]) // 车间选项列表
const unitOptions = ref<{ id: number; name: string }[]>([]) // 单位选项列表
const formData = ref({
  id: undefined,
  energyId: undefined,
  energyName: '',
  workshopId: undefined,
  workshopName: '',
  unitId: undefined,
  unitName: '',
  energyTime: undefined,
  energyValue: undefined
})
const formRules = reactive({
  energyId: [{ required: true, message: '请选择能耗表', trigger: 'change' }],
  //workshopId: [{ required: true, message: '请选择所属车间', trigger: 'change' }],
  unitId: [{ required: true, message: '请选择能耗单位', trigger: 'change' }],
  energyTime: [{ required: true, message: '能耗时间不能为空', trigger: 'blur' }],
  energyValue: [{ required: true, message: '能耗值不能为空', trigger: 'blur' }]
})

/** 能耗表选择变更事件 */
const handleEnergyChange = () => {
  if (formData.value.energyId) {
    const selectedEnergy = energyOptions.value.find((item) => item.id === formData.value.energyId)
    if (selectedEnergy) {
      formData.value.energyName = selectedEnergy.name
    }
  } else {
    formData.value.energyName = ''
  }
}

/** 车间选择变更事件 */
// const handleWorkshopChange = () => {
//   if (formData.value.workshopId) {
//     const selectedWorkshop = workshopOptions.value.find(
//       (item) => item.id === formData.value.workshopId
//     )
//     if (selectedWorkshop) {
//       formData.value.workshopName = selectedWorkshop.name
//     }
//   } else {
//     formData.value.workshopName = ''
//   }
// }

/** 单位选择变更事件 */
const handleUnitChange = () => {
  if (formData.value.unitId) {
    const selectedUnit = unitOptions.value.find((item) => item.id === formData.value.unitId)
    if (selectedUnit) {
      formData.value.unitName = selectedUnit.name
    }
  } else {
    formData.value.unitName = ''
  }
}
const formRef = ref() // 表单 Ref

/** 获取能耗表列表 */
const getEnergyList = async () => {
  try {
    const { list } = await EnergyApi.getEnergyPage({ pageSize: 100 })
    energyOptions.value = list.map((item) => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('获取能耗表列表失败', error)
  }
}

/** 获取车间列表 */
const getWorkshopList = async () => {
  try {
    const { list } = await EnergyWorkshopApi.getEnergyWorkshopPage({ pageSize: 100 })
    workshopOptions.value = list.map((item) => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('获取车间列表失败', error)
  }
}

/** 获取单位列表 */
const getUnitList = async () => {
  try {
    const { list } = await EnergyUnitApi.getEnergyUnitPage({ pageSize: 100 })
    unitOptions.value = list.map((item) => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('获取单位列表失败', error)
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 获取能耗表、车间和单位列表
  await Promise.all([getEnergyList(), getWorkshopList(), getUnitList()])

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await EnergyReportApi.getEnergyReport(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as EnergyReportVO
    if (formType.value === 'create') {
      await EnergyReportApi.createEnergyReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await EnergyReportApi.updateEnergyReport(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    energyId: undefined,
    energyName: '',
    workshopId: undefined,
    workshopName: '',
    unitId: undefined,
    unitName: '',
    energyTime: undefined,
    energyValue: undefined
  }
  formRef.value?.resetFields()
}
</script>
